package org.zhangkun.jmsg.ui.swing;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.border.EmptyBorder;

import org.zhangkun.jmsg.bean.DataPack;
import org.zhangkun.jmsg.bean.DataPackage;
import org.zhangkun.jmsg.bean.SendMsgInfo;
import org.zhangkun.jmsg.bean.User;
import org.zhangkun.jmsg.core.UserManager;
import org.zhangkun.jmsg.core.listener.RecvMsgListener;
import org.zhangkun.jmsg.core.network.MsgTransport;
import org.zhangkun.jmsg.core.network.filetransport.FileTransport;
import org.zhangkun.jmsg.core.network.filetransport.SendFiles;
import org.zhangkun.jmsg.ui.swing.view.FilesTable;
import org.zhangkun.jmsg.ui.swing.view.UserTreePanel;
import org.zhangkun.jmsg.util.FileScanner;
import org.zhangkun.jmsg.util.ObjectUtil;
import org.zhangkun.jmsg.util.ScannerFilesListener;

public class SendFileDialog extends JFrame implements ScannerFilesListener,
		DropTargetListener, RecvMsgListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5650537734469588210L;
	private JButton addBtn;
	private ArrayList<SendFiles> allSF;
	private final JPanel contentPanel = new JPanel();
	private JFileChooser jfc = new JFileChooser();
	private JButton okButton;
	private JProgressBar progressBar;
	private String[] selFiles;
	private ArrayList<SendFiles> sendFailUser = new ArrayList<SendFiles>();
	private SendFiles sf;
	private FileScanner sfl;
	private JButton skipScanBtn;
	private FilesTable table;
	private UserTreePanel userTreePanel;
	private JLabel waitMsg;
	private JPanel panel_1;

	public SendFileDialog() {
		// TODO Auto-generated constructor stub
		setIconImage(UserManager.me.getPhoto());
		sf = new SendFiles();
		setTitle("发送文件");
		initGUI();
		this.setVisible(true);
	}

	/**
	 * Create the dialog.
	 */
	public SendFileDialog(User user) {
		this();
		userTreePanel.selUser(user);
	}

	public UserTreePanel getUserTreePanel() {
		return userTreePanel;
	}

	public void setUserTreePanel(UserTreePanel userTreePanel) {
		this.userTreePanel = userTreePanel;
	}

	@Override
	public void acceptRecvMsg(SendMsgInfo sendMsgInfo, boolean result) {
		// TODO Auto-generated method stub
		// for (int i = 0; i < allSF.size(); i++) {
		SendFiles sf = (SendFiles) sendMsgInfo.getOtherData();
		// if (sf.getPackageID().equals(sendMsgInfo.getDp().getDataID())) {
		if (result) {
			allSF.remove(sf);
			sf.startUp();
		} else {
			allSF.remove(sf);
			sendFailUser.add(sf);
		}
		// }
		// }

		if (allSF.size() == 0) {
			if (sendFailUser.size() != 0) {

			}
		}

	}

	public void addPath() {
		sfl = new FileScanner();
		for (int i = 0; i < this.selFiles.length; i++) {
			if (!isExists(selFiles[i]))
				sfl.append(selFiles[i]);
		}
		sfl.setListener(this);
		sfl.start();
		updateScanComponent(true);
	}

	private void cancel() {
		if (sf.getFmps().size() != 0) {
			if (JOptionPane.showConfirmDialog(SendFileDialog.this,
					"您确认取消发送这些文件吗？", "警告", JOptionPane.OK_OPTION
							| JOptionPane.CANCEL_OPTION) == JOptionPane.OK_OPTION) {
				sf.setStatus(FileTransport.STATUS_USER_CANCEL);
				this.setVisible(false);
				close();
				this.dispose();
			} else {
				this.setVisible(true);
			}
		} else {
			sf.setStatus(FileTransport.STATUS_USER_CANCEL);
			this.setVisible(false);
			close();
			this.dispose();
		}
	}

	public void close() {
		UserManager.removeUserListener(userTreePanel);
	}

	@Override
	public void dragEnter(DropTargetDragEvent dtde) {
		// TODO Auto-generated method stub

	}

	@Override
	public void dragExit(DropTargetEvent dte) {
		// TODO Auto-generated method stub

	}

	@Override
	public void dragOver(DropTargetDragEvent dtde) {
		// TODO Auto-generated method stub

	}

	@Override
	public void drop(DropTargetDropEvent dtde) {
		// TODO Auto-generated method stub
		System.out.println(dtde);
		try {
			dtde.getTransferable();
			if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
				dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
				System.out.println("file cp");
				List<?> list = (List<?>) (dtde.getTransferable()
						.getTransferData(DataFlavor.javaFileListFlavor));
				selFiles = new String[list.size()];
				Object obj;
				for (int i = 0; i < list.size(); i++) {
					obj = list.get(i);
					if (obj instanceof String)
						selFiles[i] = (String) obj;
					else if (obj instanceof File)
						selFiles[i] = ((File) obj).getAbsolutePath();

				}
				dtde.dropComplete(true);
				addPath();
				// this.updateUI();
			} else if (dtde.isDataFlavorSupported(DataFlavor.stringFlavor)) {
				dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
				// System.out.println("file cp");
				String s = (String) (dtde.getTransferable()
						.getTransferData(DataFlavor.stringFlavor));
				s = URLDecoder.decode(s, "utf-8");
				s = s.replaceAll("file://", "");
				selFiles = s.split("\r\n");
				for (String ss : selFiles)
					System.out.println(ss);
				// List list =
				// selFiles = new File[list.size()];
				addPath();
				dtde.dropComplete(true);
			} else {
				dtde.rejectDrop();
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (UnsupportedFlavorException ufe) {
			ufe.printStackTrace();
		}
	}

	@Override
	public void dropActionChanged(DropTargetDragEvent dtde) {
		// TODO Auto-generated method stub

	}

	@Override
	public void finishScan(String path, long allSize, boolean b) {
		// TODO Auto-generated method stub
		table.addPath(sf.appendPath(path, allSize));
		if (b)
			updateScanComponent(false);

	}

	private void initGUI() {
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				cancel();
			}
		});
		// setBounds(100, 100, 700, 600);
		setSize(700, 600);
		setLocationRelativeTo(null);
		getContentPane().setLayout(new BorderLayout());
		{
			{
				jfc.setDialogTitle("添加文件");
				jfc.setMultiSelectionEnabled(true);
				jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
			}
		}
		{
			userTreePanel = new UserTreePanel("选择好友",
					UserTreePanel.SHOW_MODEL_SELECTION);
			getContentPane().add(userTreePanel, BorderLayout.EAST);
		}
		{
			panel_1 = new JPanel();
			getContentPane().add(panel_1, BorderLayout.CENTER);
			panel_1.setLayout(new BorderLayout(0, 0));
			{
				JPanel buttonPane = new JPanel();
				panel_1.add(buttonPane, BorderLayout.SOUTH);
				buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
				{
					okButton = new JButton("发送");
					okButton.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							ArrayList<User> allSendUser = userTreePanel
									.getSelUser();
							allSF = new ArrayList<SendFiles>();
							allSF.add(sf);
							if (allSendUser.size() == 0) {
								JOptionPane.showMessageDialog(
										SendFileDialog.this, "您必须至少选择一个好友接收！");
								return;
							}
							for (int i = 1; i < allSendUser.size(); i++)
								try {
									allSF.add((SendFiles) ObjectUtil
											.cloneObject(sf));
								} catch (IOException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								} catch (ClassNotFoundException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
							for (int i = 0; i < allSF.size(); i++) {
								DataPack dp = new DataPack();
								dp.setDataType(DataPackage.IPMSG_SENDMSG
										| DataPackage.IPMSG_SENDCHECKOPT
										| DataPackage.IPMSG_FILEATTACHOPT);
								dp.setMsg(allSF.get(i).getMsg());
								dp.setSendToHostAddres(allSendUser.get(i)
										.getIp());
								SendMsgInfo smi = new SendMsgInfo(dp,
										SendFileDialog.this, true);
								smi.setOtherData(allSF.get(i));
								MsgTransport.instance.addMsg(smi);
								allSF.get(i).setUser(allSendUser.get(i));
								allSF.get(i).setPackageID(dp.getDataID());
							}
							setVisible(false);
							close();
							dispose();
						}
					});
					{
						waitMsg = new JLabel("计算大小中:");
						waitMsg.setVisible(false);
						buttonPane.add(waitMsg);
					}
					{
						progressBar = new JProgressBar();
						progressBar.setVisible(false);
						buttonPane.add(progressBar);
					}
					{
						skipScanBtn = new JButton("跳过");
						skipScanBtn.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent e) {
								sfl.setStop(true);
								updateScanComponent(false);
							}
						});
						skipScanBtn.setVisible(false);
						buttonPane.add(skipScanBtn);
					}
					okButton.setActionCommand("OK");
					okButton.setEnabled(false);
					buttonPane.add(okButton);
					getRootPane().setDefaultButton(okButton);
				}
				{
					JButton cancelButton = new JButton("取消");
					cancelButton.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							cancel();
						}
					});
					cancelButton.setActionCommand("Cancel");
					buttonPane.add(cancelButton);
				}
			}

			panel_1.add(contentPanel, BorderLayout.CENTER);
			contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
			contentPanel.setLayout(new BorderLayout(0, 0));
			{
				table = new FilesTable();
				table.init(sf.getFmps(), "");
				contentPanel.add(table);
			}
			JPanel panel = new JPanel();
			contentPanel.add(panel, BorderLayout.SOUTH);
			{
				addBtn = new JButton("添加");
				addBtn.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						if (jfc.showDialog(SendFileDialog.this, "添加") == JFileChooser.APPROVE_OPTION) {
							File[] fs = jfc.getSelectedFiles();
							selFiles = new String[fs.length];
							for (int i = 0; i < fs.length; i++)
								selFiles[i] = fs[i].getAbsolutePath();
							addPath();
						}
					}
				});
				panel.setLayout(new BorderLayout(0, 0));
				panel.add(addBtn, BorderLayout.SOUTH);
			}
			table.setOkButton(okButton);
		}
		new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
	}

	private boolean isExists(String string) {
		// TODO Auto-generated method stub
		for (int i = 0; i < sf.getFmps().size(); i++)
			if (sf.getFmps().get(i).getPath().equals(string))
				return true;
		return false;
	}

	@Override
	public void progress(String path, int index, int allLength) {
		// TODO Auto-generated method stub
		progressBar.setValue(index * 100 / allLength);
		waitMsg.setText("计算大小:(" + index + "/" + allLength + ")");
	}

	private void updateScanComponent(boolean flag) {
		skipScanBtn.setVisible(flag);
		waitMsg.setVisible(flag);
		progressBar.setVisible(flag);
		okButton.setEnabled(!flag);
		addBtn.setEnabled(!flag);
	}
}
